<?php

namespace App\service\goods;

use Exception;
use support\Log;
use support\Redis;
use think\facade\Db;
use crmeb\exceptions\AdminException;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};

class GoodsComposeLogServices
{
    /**
     * 合成日志
     * @param array $userInfo
     * @param array $goodsInfo
     * @param array $goodsCompose
     * @param array $goods_compose_log_many
     * @param string $description
     * @return bool
     */
    public function addLog(array $userInfo, array $goodsInfo, array $goodsCompose, array $goods_compose_log_many, string $description)
    {
        //开始事务
        Db::startTrans();

        try {

            $log_id = Db::name('goods_compose_log')->insertGetId([
                'uid' => $userInfo['id'],
                'name' => $userInfo['name'],
                'mobile' => $userInfo['mobile'],
                'account_id' => $userInfo['account_id'],
                'goods_id' => $goodsInfo['id'],
                'goods_name' => $goodsInfo['name'],
                'description' => $description,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            if (!$log_id) {
                throw new AdminException('网络错误请稍后再试');
            }

            $log_info = [];

            foreach ($goodsCompose as $k => $v) {
                $log_info[] = [
                    'log_id' => $log_id,
                    'condition_goods_id' => $v['condition_goods_id'],
                    'condition_goods_name' => $v['condition_goods_name'],
                    'num' => $v['num'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }

            if (!Db::name('goods_compose_log_info')->insertAll($log_info)) {
                throw new AdminException('网络错误请稍后再试');
            }

            foreach ($goods_compose_log_many as $k => $v) {
                $goods_compose_log_many[$k]['log_id'] = $log_id;
            }

            if (!Db::name('goods_compose_log_many')->insertAll($goods_compose_log_many)) {
                throw new AdminException('网络错误请稍后再试');
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new AdminException($e->getMessage());
        }

        return true;
    }
}
